package com.sillyhat.project.redis.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化，反序列化工具类
 *
 * @author 徐士宽
 * @date 2017/5/4 12:08
 */

public class SillyHatSerializeUtils {

    private static final Logger logger = LoggerFactory.getLogger(SillyHatSerializeUtils.class);

    public static byte[] serialize(Object obj) {
        if(obj == null)
            return null;
        byte[] bytes = null;
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            bytes = baos.toByteArray();
        } catch (IOException e) {
            logger.error("序列化出现异常",e);
        } finally {
            try {
                if(baos != null)
                    baos.close();
                if(oos != null)
                    oos.close();
            } catch (IOException e) {
                logger.error("关闭OutputStream出现异常",e);
            }
        }
        return bytes;
    }

    public static Object deSerialize(byte[] bytes) {
        if(bytes == null)
            return null;
        Object obj = null;
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            obj = ois.readObject();
        } catch (Exception e) {
            logger.error("反序列化出现异常",e);
        } finally {
            try {
                if(bais != null)
                    bais.close();
                if(ois != null)
                    ois.close();
            } catch (IOException e) {
                logger.error("关闭InputStream出现异常",e);
            }
        }
        return obj;
    }
}
